package com.crm.marketing.service;

import com.crm.common.mapper.ChanceMapper;
import com.crm.common.pojo.Chance;
import com.crm.global.exception.CrmException;
import com.crm.global.exception.ExceptionEnum;
import com.crm.id.increment.IdWorker;
import com.crm.mybatis.separation.Read;
import com.crm.mybatis.separation.Write;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

@Service
public class ChanceService {

    @Autowired
    private ChanceMapper chanceMapper;

    @Write
    public void saveOrUpdate(Chance chance) {
        if (chance == null) {
            throw new CrmException(ExceptionEnum.PARAM_IS_NULL);
        }
        if(chance.getId() == null) {
            chance.setId(new IdWorker().nextId());
            chanceMapper.insert(chance);
        } else {
            chanceMapper.updateByPrimaryKey(chance);
        }
    }

    @Read
    public PageInfo<Chance> findAll(int page,int size,Chance chance) {
        PageHelper.startPage(page,size);

        chance = chance == null ? new Chance() : chance;
        Example example = new Example(Chance.class);
        Example.Criteria criteria = example.createCriteria();

        // 如果客户姓名不为空
        if (StringUtils.isNotBlank(chance.getCustomerName())) {
            criteria.orLike("customerName","%" + chance.getCustomerName() + "%");
        } else if(StringUtils.isNotBlank(chance.getLinkman())) { // 如果联系人不为空
            criteria.orLike("linkman","%" + chance.getLinkman() + "%");
        }

        return new PageInfo(chanceMapper.selectByExample(example));

    }


    @Read
    public Chance findById(long id) {
        return chanceMapper.selectByPrimaryKey(id);
    }

    @Write
    public void deleteById(long id) {
        chanceMapper.deleteByPrimaryKey(id);
    }


}
